package com.baiye.template.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.baiye.template.common.ConstantProperties;
import com.baiye.template.dao.FileDao;
import com.baiye.template.pojo.MyFile;
import com.baiye.template.service.FileService;
import com.github.pagehelper.PageHelper;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/9/9 11:14
 */
@Service
public class FileServiceImpl implements FileService {
    private final String FILE_PATH="/temp/";
    Logger log = LoggerFactory.getLogger(FileServiceImpl.class);
    @Autowired
    private FileDao fileDao;
    @Override
    public String uploadFileToOSS(MultipartFile file) {
        String endpoint= ConstantProperties.ENDPOINT;
        String accessKeyId=ConstantProperties.ACCESS_KEY_ID;
        String accessKeySecret=ConstantProperties.ACCESS_KEY_SECRET;
        String bucketName=ConstantProperties.BUCKET_NAME;
        String fileHost=ConstantProperties.FILE_HOST;
        String uploadUrl=null;
        InputStream in=null;
        try {
            in=file.getInputStream();

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            if(!ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //获取文件原始名
            String orginalName=file.getOriginalFilename();
            String fileName= UUID.randomUUID().toString();
            //原始文件后缀名
            String fileType=orginalName.substring(orginalName.lastIndexOf("."));
            String newFileName=fileName+fileType;

            String filePath=new DateTime().toString("YYYY/MM/DD");

            // 创建PutObjectRequest对象。
            // 填写Bucket名称、Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
            // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
            String fileUrl=fileHost+"/"+filePath+"/"+newFileName;


            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl, in);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            ossClient.putObject(putObjectRequest);

            uploadUrl="https://"+bucketName+"."+endpoint+"/"+fileUrl;

            // 关闭OSSClient。
            ossClient.shutdown();
        }catch (IOException e){
            log.info(e.getMessage());
        }
        return uploadUrl;
    }

    @Override
    public String uploadFileToLocal(MultipartFile file,Integer userId) {
        String originalFilename=file.getOriginalFilename();
        File file1 = new File("d:\\temp\\"+originalFilename);
        if (!file1.getParentFile().exists()) {
            file1.getParentFile().mkdir();
        }
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url=FILE_PATH+originalFilename;
        MyFile myfile = new MyFile();
        myfile.setUserId(userId);
        myfile.setName(originalFilename);
        myfile.setUrl(url);
        myfile.setCreatTime(new Date());
        fileDao.saveFile(myfile);
        return url;
    }

    @Override
    public List<MyFile> getFile(MyFile myFile, Integer pageIndex, Integer pageSize) {
        int start = (pageIndex-1)*pageSize;
        PageHelper.startPage(pageIndex,pageSize);
        return fileDao.getFile(myFile,start,pageSize);
    }
}
